package com.Tokiu.web;

import com.Tokiu.web.Util.sqlsessionfactoryDemo;
import com.Tokiu.web.mapper.userMapper;
import com.Tokiu.web.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        //1.接收用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //2.调用mybatis完成查询
        //2.1 获取sqlsessionfactory对象

//        String resource = "mybatis-config.xml";
//        InputStream inputStream = Resources.getResourceAsStream(resource);
//        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //调用封装的sqlsessionFactory对象
        SqlSessionFactory sqlSessionFactory = sqlsessionfactoryDemo.Getsqlsessionfactory();
        //2.2 获取sqlsession对象

        SqlSession sqlSession = sqlSessionFactory.openSession();
        //2.3获取mapper

        userMapper mapper = sqlSession.getMapper(userMapper.class);
        //2.4调用方法
        User user = mapper.select(username, password);
        //2.5释放资源
        sqlSession.close();

        System.out.println(user);
        //3.判断

        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();

        if(user!=null)
        {
            writer.println("<h1>登陆成功！</h1>");
        }else {
            writer.println("<h1>登陆失败！</h1>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
